// WebSocket连接管理器
class WebSocketManager {
  constructor() {
    this.ws = null;
    this.isConnected = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 3;
    this.reconnectInterval = 3000; // 3秒
    this.connecting = false;
    this.needReconnect = true; // 是否需要重连的标志
  }

  // 初始化WebSocket连接
  init() {
    if (this.connecting) {
      console.log("WebSocket正在连接中...");
      return;
    }

    if (this.ws) {
      this.close();
    }

    this.connecting = true;
    this.needReconnect = true; // 初始化时允许重连

    // 创建WebSocket连接
    this.ws = uni.connectSocket({
      url: "wss://fishpi.cn/login-channel",
      success: () => {
        console.log("WebSocket连接创建成功");
      },
      fail: (err) => {
        console.error("WebSocket连接创建失败:", err);
        this.connecting = false;
        this.handleReconnect();
      },
    });

    // 监听连接打开
    uni.onSocketOpen(() => {
      console.log("WebSocket连接已打开");
      this.isConnected = true;
      this.connecting = false;
      this.reconnectAttempts = 0;
    });

    // 监听连接关闭
    uni.onSocketClose(() => {
      console.log("WebSocket连接已关闭");
      this.isConnected = false;
      this.connecting = false;
      if (this.needReconnect) {
        this.handleReconnect();
      }
    });

    // 监听连接错误
    uni.onSocketError((err) => {
      console.error("WebSocket连接错误:", err);
      this.isConnected = false;
      this.connecting = false;
      if (this.needReconnect) {
        this.handleReconnect();
      }
    });

    // 监听消息
    uni.onSocketMessage((res) => {
      console.log("收到WebSocket消息:", res);
      this.handleMessage(res.data);
    });
  }

  // 处理重连
  handleReconnect() {
    if (
      this.reconnectAttempts < this.maxReconnectAttempts &&
      !this.connecting &&
      this.needReconnect
    ) {
      this.reconnectAttempts++;
      console.log(
        `尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`
      );
      setTimeout(() => {
        this.init();
      }, this.reconnectInterval);
    } else if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log("达到最大重连次数，停止重连");
      this.connecting = false;
    }
  }

  // 发送消息
  send(data) {
    if (!this.isConnected) {
      console.error("WebSocket未连接");
      return false;
    }

    return new Promise((resolve, reject) => {
      try {
        uni.sendSocketMessage({
          data: typeof data === "string" ? data : JSON.stringify(data),
          success: () => {
            console.log("消息发送成功");
            resolve(true);
          },
          fail: (err) => {
            console.error("消息发送失败:", err);
            reject(err);
          },
        });
      } catch (error) {
        console.error("发送消息时发生错误:", error);
        reject(error);
      }
    });
  }

  // 处理接收到的消息
  handleMessage(data) {
    try {
      const message = JSON.parse(data);
      // 这里可以添加消息处理逻辑
      console.log("处理消息:", message);
    } catch (error) {
      console.error("解析消息失败:", error);
    }
  }

  // 关闭连接
  close() {
    this.needReconnect = false; // 关闭连接时禁用重连
    if (this.ws && this.isConnected) {
      uni.closeSocket({
        success: () => {
          console.log("WebSocket连接已关闭");
          this.isConnected = false;
          this.connecting = false;
        },
        fail: (err) => {
          console.error("关闭WebSocket连接失败:", err);
          this.isConnected = false;
          this.connecting = false;
        },
      });
    } else {
      this.isConnected = false;
      this.connecting = false;
    }
  }
}

// 创建单例实例
const wsManager = new WebSocketManager();

export default wsManager;
